﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SFWS.XHandler.Core;
using JKF.Substructure;
using JKF.BusinessLayer.BLL;
using JKF.Entities;
using System.Data;

namespace JKF.HandlerLayer.Product
{
    public partial class Stock_OutHandler:AHttpHandler
    {
        private static bllSTOCK_OUT bllStock_Out = new bllSTOCK_OUT();
        public override void ProcessRequest()
        {
            //所有错误和异常将抛出异常.正常执行程序则在方法则返回数据
            try
            {
                this.Manager(Utils.GetActionName);
            }
            catch (Exception ex)
            {
                //将错误抛到客户端(以Json格式)
                Utils.ToClient(true, ex.Message);
                //写日志
                AppLogger.Log(ex.Message, ex);
            }
        }
        /// <summary>
        /// 产品/耗材出库
        /// </summary> 
        public void InsertStock_Out()
        {
            try
            {
                var strScr = P("moduleObj");
                var productInfo = this.BuildStock_OutinfoByJson(JsonSerializer.Deserialize<Stock_OutTemp>(strScr), false);
                // 执行出库时，需要同步更新dbo.STOCK_AMOUNT 表中记录 
                Response.Write(JsonSerializer.Serialize(
                    new ResponseInf
                    {
                        MessageCode = "Ok",
                        Message = "出库成功.",
                        Data = new { OUT_KEY = productInfo.OUT_KEY, OUT_NO = productInfo.OUT_NO, USER_NAME = bllSYS_USER.CurrentUser.REAL_NAME },
                        Success = bllStock_Out.TransationSql(BuildStock_Out_InsertSqlByModel(productInfo))
                    }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }
        
        /// <summary>
        /// 产品/耗材出库编辑
        /// </summary>
        public void EditStock_Out()
        {
            try
            {
                var strScr = P("moduleObj");
                var productInfo = this.BuildStock_OutinfoByJson(JsonSerializer.Deserialize<Stock_OutTemp>(strScr), true);
                // 修改入库时，(暂时保留，以便后续用)需要同步更新dbo.STOCK_AMOUNT 表中记录 
                string stock_amount_update_sql = string.Format(" update dbo.STOCK_AMOUNT set PRODUCT_NUMS=PRODUCT_NUMS-{0}+{1} where PRODUCT_KEY='{2}' and SHOP_CODE='{3}' ;", productInfo.PRODUCT_NUMS, productInfo.OLD_PRODUCT_NUMS, productInfo.PRODUCT_KEY, productInfo.SHOP_CODE);
                string stock_out_update_sql = string.Format(" update dbo.STOCK_OUT set PRODUCT_NUMS={0},DATE_OUT='{1}',MEMO='{2}',DATE_UPDATE='{3}' where OUT_KEY='{4}'", productInfo.PRODUCT_NUMS, productInfo.DATE_OUT, productInfo.MEMO, productInfo.DATE_UPDATE, productInfo.OUT_KEY);
                Response.Write(JsonSerializer.Serialize(
                    new ResponseInf
                    {
                        MessageCode = "Ok",
                        Message = "修改成功.",
                        Data = new { OUT_KEY = productInfo.OUT_KEY, OUT_NO = productInfo.OUT_NO, USER_NAME = bllSYS_USER.CurrentUser.REAL_NAME },
                        Success = bllStock_Out.TransationSql(stock_out_update_sql + stock_amount_update_sql)
                    }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }
        /// <summary>
        /// 获取每个店铺的出库列表数据
        /// </summary>
        public void GetSTOCK_OUTS()
        {
            var obj = new PagerList();

            int pageCount = 0;
            int rowCount = 0;
            //从视图中获取
            obj.Entity = from a in bllStock_Out.GetStock_OutsBLL(bllSYS_USER.CurrentUser.SHOP_CODE, P("PRODUCT_KEY"), P("PRODUCT_NUMS"), P("OUT_NO"), P("REAL_NAME"), P("MEMO"), P("DATA_START"), P("DATA_END"), P("PageIndex").ToInt32(), P("PageSize").ToInt32(), ref pageCount, ref rowCount).AsEnumerable()
                         select new
                         {//PRODUCT_KEY, NAME, MODEL, TYPE, IN_NO, DATE_IN, MEMO, SORT_NAME, SHOP_CODE, PRODUCT_NUMS, USER_CREATE, 
                             OUT_KEY = a.Field<Guid>("OUT_KEY"),
                             OUT_NO = a.Field<string>("OUT_NO"), //出库单号
                             SORT_NAME = a.Field<string>("SORT_NAME"), //产品类别名称
                             NAME = a.Field<string>("NAME"), //产品名称
                             PRODUCT_NUMS = a.Field<int>("PRODUCT_NUMS"), //出库数量
                             MEMO = a.Field<string>("MEMO"), //备注
                             USER_CREATE = a.Field<string>("USER_CREATE"), //操作员姓名
                             DATE_CREATE = (a.Field<DateTime>("DATE_CREATE")).ToString("yyyy-MM-dd")
                         };

            obj.RowCount = rowCount;
            obj.PageCount = pageCount;
            ResponseJsonObject = obj;
        }
        
        /// <summary>
        /// 根据出库主键获取出库记录
        /// </summary>
        public void GetStock_OutByCode()
        {
            try
            {
                var scid = P("moduleKey");
                var stock_out_model = bllStock_Out.GetModel(new Guid(scid));
                var stock_out_product_model = new bllPRODUCT().GetModel(stock_out_model.PRODUCT_KEY);
                Response.Write(JsonSerializer.Serialize(
                    new ResponseInf
                    {
                        MessageCode = "Ok",
                        Data = stock_out_model,
                        Mode = new { SORT_KEY = stock_out_product_model.SORT_KEY, TYPE = stock_out_product_model.TYPE },
                        FormatString = stock_out_model.DATE_OUT.ToString("yyyy-MM-dd")
                    }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }
        /// <summary>
        /// 根据主键IN_KEY删除入库记录，采用逻辑删除
        /// </summary>
        public void DeleteSTOCK_OUT()
        {
            try
            {
                var out_key = P("id");
                string stock_out_delete_sql = string.Format("update dbo.STOCK_OUT set STATUS=9 where OUT_KEY='{0}'", out_key);
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Ok", Success = bllStock_Out.TransationSql(stock_out_delete_sql), Data = out_key }));

            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }
        /// <summary>
        /// 从Json对象构建对象
        /// </summary>
        /// <param name="shopInfo">实体对象</param>
        /// <param name="isEdit">是否为编辑</param>
        /// <returns></returns>
        public Stock_OutTemp BuildStock_OutinfoByJson(Stock_OutTemp stock_out_info, bool isEdit)
        {
            var entity = new Stock_OutTemp();
            if (!isEdit) // 添加
            {
                entity.OUT_KEY = new Guid(DB.GetNewGuid(DB.HR)); //Guid.NewGuid();
                entity.OUT_NO = this.BuildStock_Out_NO(bllSYS_USER.CurrentUser.SHOP_CODE);//这个需要算法来自动生成
            }
            else // 修改
            {
                entity.OUT_KEY = stock_out_info.OUT_KEY;
                entity.OUT_NO = stock_out_info.OUT_NO;
            }

            entity.MEMO = stock_out_info.MEMO;
            entity.PRODUCT_KEY = stock_out_info.PRODUCT_KEY;
            entity.PRODUCT_NUMS = stock_out_info.PRODUCT_NUMS;
            entity.OLD_PRODUCT_NUMS = stock_out_info.OLD_PRODUCT_NUMS;
            entity.SHOP_CODE = bllSYS_USER.CurrentUser.SHOP_CODE; //当前用户店面编码
            entity.DATE_OUT = stock_out_info.DATE_OUT;
            entity.USER_CREATE = bllSYS_USER.CurrentUser.USER_KEY; // 获取当前用户guid
            entity.DATE_CREATE = System.DateTime.Now.ToString();
            entity.DATE_UPDATE = System.DateTime.Now.ToString();
            return entity;
        }
        
        /// <summary>
        /// 通过实体来构成插入语句
        /// </summary>
        /// <param name="stock_in_temp"></param>
        /// <returns></returns>
        public string BuildStock_Out_InsertSqlByModel(Stock_OutTemp stock_out_temp)
        {//OUT_KEY, PRODUCT_KEY, OUT_NO, PRODUCT_NUMS, DATE_OUT, MEMO, STATUS, SHOP_CODE, USER_CREATE, DATE_CREATE, DATE_UPDATE
            string stock_amount_sql = string.Empty;
            string stock_out_sql = string.Format("insert into dbo.STOCK_OUT(OUT_KEY, PRODUCT_KEY, OUT_NO, PRODUCT_NUMS, DATE_OUT, MEMO, SHOP_CODE, USER_CREATE, DATE_CREATE, DATE_UPDATE, STATUS) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','1');", stock_out_temp.OUT_KEY, stock_out_temp.PRODUCT_KEY, stock_out_temp.OUT_NO, stock_out_temp.PRODUCT_NUMS, stock_out_temp.DATE_OUT, stock_out_temp.MEMO, stock_out_temp.SHOP_CODE,stock_out_temp.USER_CREATE,stock_out_temp.DATE_CREATE,stock_out_temp.DATE_UPDATE);
            //1.先判断出库的产品dbo.STOCK_AMOUNT表中是否存在(product_key,shop_code)，如果存在则更新
            if (new bllSTOCK_AMOUNT().Exists(stock_out_temp.PRODUCT_KEY, stock_out_temp.SHOP_CODE))
            {
                stock_amount_sql = string.Format(" update dbo.STOCK_AMOUNT set PRODUCT_NUMS=PRODUCT_NUMS-{0}+{1} where PRODUCT_KEY='{2}' and SHOP_CODE='{3}'", stock_out_temp.PRODUCT_NUMS, stock_out_temp.OLD_PRODUCT_NUMS, stock_out_temp.PRODUCT_KEY, stock_out_temp.SHOP_CODE);
            }
            else
            {
                stock_amount_sql = string.Format(" insert into dbo.STOCK_AMOUNT(PRODUCT_KEY, SHOP_CODE, PRODUCT_NUMS, USER_CREATE, DATE_CREATE, DATE_UPDATE) VALUES('{0}','{1}','-{2}','{3}','{4}','{5}')", stock_out_temp.PRODUCT_KEY, stock_out_temp.SHOP_CODE, stock_out_temp.PRODUCT_NUMS, stock_out_temp.USER_CREATE, stock_out_temp.DATE_CREATE, stock_out_temp.DATE_UPDATE);
            }
            return stock_out_sql + stock_amount_sql;
        } 
        /// <summary>
        /// 生成出库单号
        /// </summary>
        /// <returns></returns>
        public string BuildStock_Out_NO(string shop_code)
        {
            return bllStock_Out.GetStock_OUT_NOBLL(shop_code);
        }
        
         
        /// <summary>
        /// 此类专用于前台传值从JSON对象构成实体对象
        /// </summary>
        public class Stock_OutTemp
        {
            /// <summary>
            /// 主键，出库表
            /// </summary>
            public Guid OUT_KEY { get; set; }
            /// <summary>
            /// 产品ID
            /// </summary>
            public Guid PRODUCT_KEY { get; set; }
            /// <summary>
            /// 出库单号
            /// </summary>
            public string OUT_NO { get; set; }
            /// <summary>
            /// 出库数量（新）
            /// </summary>
            public string PRODUCT_NUMS { get; set; }
            /// <summary>
            /// 出库数量（旧）
            /// </summary>
            public string OLD_PRODUCT_NUMS { get; set; }
            /// <summary>
            /// 出库日期
            /// </summary>
            public string DATE_OUT { get; set; }
            /// <summary>
            /// 备注
            /// </summary>
            public string MEMO { get; set; }
            /// <summary>
            /// 店铺
            /// </summary>
            public string SHOP_CODE { get; set; }
            /// <summary>
            /// 创建者ID
            /// </summary>
            public Guid USER_CREATE { get; set; }
            /// <summary>
            /// 创建日期
            /// </summary>
            public string DATE_CREATE { get; set; }
            /// <summary>
            /// 修改日期
            /// </summary>
            public string DATE_UPDATE { get; set; }
        }

    }
}
